package com.zxh.blog.solr.impl;

import com.zxh.blog.solr.SolrService;
import com.zxh.blog.solr.dto.UserDTO;
import org.apache.solr.client.solrj.SolrQuery;
import org.apache.solr.client.solrj.SolrServerException;
import org.apache.solr.client.solrj.impl.HttpSolrClient;
import org.apache.solr.client.solrj.response.QueryResponse;
import org.apache.solr.client.solrj.response.UpdateResponse;
import org.apache.solr.common.SolrInputDocument;
import org.springframework.stereotype.Service;

import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

/**
 * @Author:wb-zxh410423
 * @Description:对于solr的增删改查
 * @Date: Created in 10:56 2018/12/14
 */
@Service
public class solrServiceImpl implements SolrService {

	HttpSolrClient solrClient = new HttpSolrClient.Builder("http://localhost:8080/solr/new_core").withSocketTimeout(60000).build();

	public void add(){
		SolrInputDocument doc = new SolrInputDocument();
		doc.addField("proname","");
		try {
			UpdateResponse rsp = solrClient.add(doc);
			solrClient.commit();
			solrClient.optimize();
		}catch (IOException e) {
			e.printStackTrace();
		} catch (SolrServerException e) {
			e.printStackTrace();
		}
	}

	public void delete(){
		try {
			UpdateResponse response = solrClient.deleteByQuery("");
			solrClient.commit();
			solrClient.optimize();
		}catch (IOException e) {
			e.printStackTrace();
		} catch (SolrServerException e) {
			e.printStackTrace();
		}

	}

	/**
	 * 文档对象中一般必须包含一个id域，所有的域的名称必须在schema.xml中定义。
	 */
	public void update(){
		HashMap<String, Object> oper = new HashMap<String, Object>();
		oper.put("set", "");
		SolrInputDocument doc = new SolrInputDocument();
		doc.addField("id", "");
		doc.addField("proname", oper);

		try {
			UpdateResponse rsp = solrClient.add(doc);
			solrClient.commit();
			solrClient.optimize();
		} catch (IOException e) {
			e.printStackTrace();
		} catch (SolrServerException e) {
			e.printStackTrace();
		}
	}

	public List query(String nickname){
		SolrQuery query = new SolrQuery();
		query.setQuery("nickname:"+nickname);
//		query.setStart(pageNum);
//		query.setRows(pageSize);
		/*
		query.setStart(0); //设置分页：起始页
		query.setRows(10); //设置分页：页面大小
		query.set("df", "item_title"); //设置默认搜索域，若不指定默认搜索域，默认从text中找
		query.setHighlight(true); //开启高亮
		query.addHighlightField("item_title"); //设置高亮的域
		query.setHighlightSimplePre("<em>"); //设置高亮的前缀
		query.setHighlightSimplePost("</em>"); //设置高亮的后缀
		*/
		List<UserDTO> userList = new ArrayList();
		try {
			QueryResponse response = solrClient.query(query);
//			SolrDocumentList documentList = response.getResults();
			userList = response.getBeans(UserDTO.class);
//			for (SolrDocument solrDocument : documentList) {
//				System.out.println(solrDocument.get("id"));
//			}
		} catch (SolrServerException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}
		return userList;
	}

}
